package com.example.learningnote.utils;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.Set;

public class Memory {
    private static final String PREFS_NAME = "app_prefs";
    private static Memory instance;
    private final SharedPreferences prefs;

    // 私有构造函数，防止外部实例化
    private Memory(Context context) {
        prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    }

    // 获取单例实例，需传入 Context（推荐使用 Application Context）
    public static synchronized Memory getInstance(Context context) {
        if (instance == null) {
            instance = new Memory(context.getApplicationContext());
        }
        return instance;
    }

    // 存储方法
    public void set(String key, String value) {
        prefs.edit().putString(key, value).apply();
    }

    public void set(String key, int value) {
        prefs.edit().putInt(key, value).apply();
    }

    public void set(String key, long value) {
        prefs.edit().putLong(key, value).apply();
    }

    public void set(String key, float value) {
        prefs.edit().putFloat(key, value).apply();
    }

    public void set(String key, boolean value) {
        prefs.edit().putBoolean(key, value).apply();
    }

    public void set(String key, Set<String> value) {
        prefs.edit().putStringSet(key, value).apply();
    }

    // 读取方法
    public String get(String key, String defaultValue) {
        return prefs.getString(key, defaultValue);
    }

    public int get(String key, int defaultValue) {
        return prefs.getInt(key, defaultValue);
    }

    public long get(String key, long defaultValue) {
        return prefs.getLong(key, defaultValue);
    }

    public float get(String key, float defaultValue) {
        return prefs.getFloat(key, defaultValue);
    }

    public boolean get(String key, boolean defaultValue) {
        return prefs.getBoolean(key, defaultValue);
    }

    public Set<String> get(String key, Set<String> defaultValue) {
        return prefs.getStringSet(key, defaultValue);
    }

    // 删除指定键
    public void remove(String key) {
        prefs.edit().remove(key).apply();
    }

    // 清空所有数据
    public void clear() {
        prefs.edit().clear().apply();
    }
}
